<?php
class FileCheckService
{
	public function __construct()
	{
	}
	
	public function checkFiles()
	{
		$baseDir = substr(dirname(__FILE__), 0, strrpos(__FILE__, "pisces"));
		$md5File = $baseDir.'pisces'.DIRECTORY_SEPARATOR.'install'.DIRECTORY_SEPARATOR.'filemd5.conf.php';
		$fileMd5 = include_once($md5File);
		if(empty($fileMd5))
		{
			return array();
		}
		
		$result = array();
		foreach($fileMd5 as $file=>$md5)
		{
			$file = str_replace("/", DIRECTORY_SEPARATOR, $file);
			if(!is_file($baseDir.$file))
			{
				//文件丢失
				$result[$file] = 1;
				continue;
			}
			$newMd5 = md5_file($baseDir.$file);
			if($newMd5 != $md5)
			{
				//文件被修改
				$result[$file] = 2;
			}
		}
		
		return $result;
	}
	
	public function getFileMd5()
	{
		$result = array();
		$files = $this->getFiles();
		$baseDir = substr(dirname(__FILE__), 0, strrpos(__FILE__, "pisces"));
		$len = strlen($baseDir);
		foreach($files as $f)
		{
			$key = substr($f, $len);
			$key = str_replace("\\", '/', $key);
			$result[$key] = md5_file($f);
		}
	}
	
	private function getFiles()
	{
		$baseDir = substr(dirname(__FILE__), 0, strrpos(__FILE__, "pisces"));
		$files = array('index.php','install.php','admin.php','pisces');
		
		$result = array();
		foreach($files as $file)
		{
			$tmp = $this->getDirFiles($baseDir.$file);
			if(!empty($tmp))
			{
				$result = array_merge($result,$tmp);
			}
		}
		
		return $result;
	}
	
	private function getDirFiles($dir)
	{
		if(is_file($dir))
		{
			return array($dir);
		}
		
		$cf = C('CommonFunction');
		$result = array();
		$files = $cf->getDirFiles($dir);
		if(!empty($files))
		{
			foreach($files as $lv)
			{
				if(strpos($lv, '.')===0 || $lv=='tmp' || $lv=='db.conf.php.sample')
				{
					continue;
				}
				
				$file = $dir.DIRECTORY_SEPARATOR.$lv;
				
				if(is_file($file))
				{
					$result[] = $file;
				}
				else
				{
					$tmp = $this->getDirFiles($file);
					if(!empty($tmp))
					{
						$result = array_merge($result,$tmp);
					}
				}
			}
		}
		
		return $result;
	}
}
?>